package com.sky.common.oss;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliyunUploadImgUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;


/**
 * 图片上传
 *        阿里云OSS云服务
 */
@Slf4j
@Validated
@Api(tags = {"OSS图片上传管理"}, description = "通用模块-阿里云OSS云对象存储")
@RestController
@RequestMapping("/admin/common")
public class OSSupLoadImgController {


    @Resource
    private AliyunUploadImgUtil aliyunUploadImgUtil;



    /**
     * 通用接口
     *         图片上传阿里云OSS云服务
     * @param file
     */
    @ApiOperation(tags = {"OSS图片上传管理"}, value = "图片上传", notes = "图片上传阿里云OSS服务")
    @PostMapping("/upload")
    public Result upLoadImgToOSS(@NotNull(message = "file文件为空")MultipartFile file){

        log.info("阿里云OSS云存储 - 图片上传，文件名: {}", file.getOriginalFilename());

        //1.判断是否有数据
        if( !file.isEmpty() ){ //有值
            // 2.获取上传文件名
            String fileName = file.getOriginalFilename();
            // 3.截取文件名后缀 .jpg  .png
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            try {
                // 4.获取上传文件IO流
                InputStream fileInputStream = file.getInputStream();
                // 5.调用OSS服务
                String imgUrl = aliyunUploadImgUtil.uploadImaToOSS(fileInputStream, suffix);
                // 6.返回
                if(StringUtils.hasLength(imgUrl)){
                    return Result.success(imgUrl);
                }
                return Result.error(MessageConstant.UPLOAD_FAILED);
            } catch (IOException e) {
                log.error("图片--fileName: {},上传阿里云OSS失败", fileName);
            }
        }

        return Result.error(MessageConstant.UPLOAD_FILE_IS_NULL);
    }



}
